import React, { PureComponent } from 'react'
import { history } from '@umijs/max'
import {
 Checkbox, Form, message, Tag, Tooltip,
} from 'antd'
import FieldMapping from 'react-field-mapping'
import { BreadcrumbBar } from '@/components'
import { offlineDetail, offlineTableFields } from './api'
import { getHashParameterByName } from '@/utils/helper'
import styles from './index.less'

const sourceCols = [
  {
    title: '源字段',
    key: 'fieldName',
    width: '2rem',
    render: (fieldName, record) => (
      <>
        {record.pk && <i className="iconfont icon-zhujian" />}
        <span>{fieldName}</span>
      </>
    ),
  },
  { title: '类型', key: 'fieldType' },
  {
    title: '非空',
    key: 'nullable',
    width: '0.5rem',
    render: (nullable) => (nullable ? '-' : '是'),
  },
  { title: '描述', key: 'comment' },
]

export default class OfflineDetail extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      id: getHashParameterByName('id'),
      menus: [{ name: '离线同步' }, { name: '查看' }],
      data: null,
      sourceFields: [],
      targetFields: [],
      relation: [],
    }
  }

  componentDidMount() {
    this.offlineDetail()
    window.onresize = () => {
      clearTimeout(this.time)
      this.time = setTimeout(() => {
        const { sourceFields, targetFields, relation } = this.state
        this.setState({
          sourceFields,
          targetFields,
          relation: [],
        }, () => {
          this.setState({
            relation,
          })
        })
      }, 500)
    }
  }

  offlineDetail = () => {
    const { id } = this.state
    console.log('id', id)
    offlineDetail({ id }).then(async (res) => {
      if (res.status === 200) {
        message.success(res.msg)
        if (!res.data) return
        let targetFields = []; let sourceFields = []; let relation = []
        if (res.data.sourceDsType === 'Kafka' || res.data.sourceDsType === 'Mongodb' || res.data.sourceDsType === 'HBase') {
          sourceFields = []
          res.data && res.data.fieldMappings && res.data.fieldMappings.map((item) => {
            sourceFields.push({
              fieldName: item.sourceField,
              fieldType: item.sourceFieldType,
              key: item.sourceField,
            })
          })
        } else {
          sourceFields = await this.offlineTableFields(0, res.data.sourceDsId, res.data.sourceTable)
        }
        if (res.data.targetDsType === 'Kafka' || res.data.targetDsType === 'Mongodb' || res.data.targetDsType === 'HBase') {
          targetFields = []
          res.data && res.data.fieldMappings && res.data.fieldMappings.map((item) => {
            targetFields.push({
              fieldName: item.targetField,
              fieldType: item.targetFieldType,
              key: item.targetField,
            })
          })
        } else {
          targetFields = await this.offlineTableFields(1, res.data.targetDsId, res.data.targetTable)
        }

        relation = await this.setRelation(res.data)
        this.setState({
          data: res.data,
          sourceFields,
          targetFields,
          cycle: res.data.schedule.cycle,
        }, () => {
          this.setState({
            relation,
          })
        })
      } else {
        message.error(res.msg)
      }
    })
  }

  offlineTableFields = (direction, dsId, tables) => new Promise((resolve, reject) => {
    offlineTableFields({ direction, dsId, tables: [tables] }).then((res) => {
      if (res.status === 200) {
        const data = res.data && res.data.tables[0] && res.data.tables[0].fields
        const dataArr = []
        data && data.map((item) => {
          item.key = item.fieldName
          item.isPk = item.pk ? 1 : 0
          if (direction === 1 && !item.isPartition) {
            dataArr.push(item)
          } else if (direction === 0) {
            dataArr.push(item)
          }
        })
        resolve(dataArr)
      } else {
        resolve([])
      }
    })
  })

  setRelation = (data) => new Promise((resolve, reject) => {
    const relation = []
    data && data.fieldMappings && data.fieldMappings.map((item) => {
      relation.push({
        source: {
          fieldName: item.sourceField,
          fieldType: item.sourceFieldType,
          isPk: item.isSourceFieldPk,
          comment: item.comment,
          key: item.sourceField,
        },
        target: {
          fieldName: item.targetField,
          fieldType: item.targetFieldType,
          isPk: item.isTargetFieldPk,
          comment: item.comment,
          key: item.targetField,
        },
      })
    })
    resolve(relation)
  })

  render() {
    const {
      menus, data, sourceFields, targetFields, relation, cycle,
    } = this.state

    return (
      <div className={`${styles.page_content_with_breadcrumb} ${styles.page_content_tabs_height}`}>
        <BreadcrumbBar menu={menus} />
        <div className={styles.back_bar}>
          <i className="iconfont icon-zuo" onClick={() => { history.push('/dataIntegrate/offline/manager') }} />
          <span onClick={() => { history.push('/dataIntegrate/offline/manager') }}>查看</span>
        </div>
        <div className={styles.page_content}>
          <div className={styles.page_content_right}>
            <Form
              labelWrap
              className={styles.form}
              colon={false}
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 20 }}
            >
              <Form.Item>
                <div className={styles.column}>基础设置</div>
              </Form.Item>
              <Form.Item
                label="任务名称"
              >
                <div className={`${styles.form_item} ${styles.text_overflow_single}`} title={data && data.taskName}>{data && data.taskName}</div>
              </Form.Item>
              <Form.Item>
                <div className={styles.column}>数据来源</div>
              </Form.Item>
              <Form.Item
                label="数据来源"
              >
                <div className={`${styles.form_item} ${styles.text_overflow_single}`} title={data && data.sourceDsName}>{data && data.sourceDsName}</div>
              </Form.Item>
              <Form.Item
                label="来源表"
              >
                <div className={`${styles.form_item} ${styles.text_overflow_single}`} title={data && data.sourceTable}>{data && data.sourceTable}</div>
              </Form.Item>
              <div>
                <Form.Item
                  label={
                    <span>
                      数据过滤
                      <Tooltip title={
                        <div>
                          <p>where 条件即针对源头数据筛选条件，根据指定的 column、table、where 条件拼接 SQL 进行数据抽取。利用 where 条件可进行全量同步和增量同步，具体说明如下：</p>
                          <p>1）全量同步：第一次做数据导入时通常为全量导入，可不用设置 where 条件。</p>
                          <p>{'2）增量同步：增量导入在实际业务场景中，往往会选择当天的数据进行同步，通常需要编写 where 条件语句，请先确认表中描述增量字段（时间戳）为哪一个。如tableA增量的字段为create_time，则填写create_time > 您需要的日期，如果需要日期动态变化，请参考帮助文档。'}</p>
                          <p>{'例如ID自增的增量同步：ID > ${to_db[select max(ID) from table_name]}'}</p>
                        </div>
                      }
                      >
                        <i className="iconfont icon-yiwentishi" />
                      </Tooltip>
                    </span>
                  }
                >
                  <div className={`${styles.form_item} ${styles.text_overflow_single}`} title={data && data.incFilter}>{data && data.incFilter}</div>
                </Form.Item>
                {/* <div
                  onClick={() => {
                    this.offlinePreviewData()
                  }}
                  className={styles.data_see}
                >数据预览
                </div> */}
              </div>
              <Form.Item>
                <div className={styles.column}>数据目标</div>
              </Form.Item>
              <Form.Item
                label="数据目标"
              >
                <div className={`${styles.form_item} ${styles.text_overflow_single}`} title={data && data.targetDsName}>{data && data.targetDsName}</div>
              </Form.Item>
              <div className={styles.target_table}>
                <Form.Item
                  label="目标表"
                >
                  <div className={`${styles.form_item} ${styles.text_overflow_single}`} title={data && data.targetTable}>{data && data.targetTable}</div>
                </Form.Item>
              </div>
              <Form.Item
                label=" "
              >
                <Checkbox checked={!!(data && data.isTruncate)} disabled>同步前清空历史数据</Checkbox>
              </Form.Item>
              <Form.Item>
                <div className={styles.column}>字段映射</div>
              </Form.Item>
              <div className={styles.field_mapping}>
                <FieldMapping
                  {...{
                    source: {
                      data: sourceFields,
                      columns: sourceCols,
                      mutiple: false,
                    },
                    target: {
                      data: targetFields,
                      columns: sourceCols,
                      mutiple: false,
                    },
                    relation,
                    edit: false,
                    onChange: (relations) => {
                      this.setState({
                        relation: relations,
                      })
                    },
                  }}
                />
              </div>
              {data && data.paritions && data.paritions.length ? <div className={styles.column}>分区字段</div> : null}
              {data && data.paritions && data.paritions.map((item) => (
                <Form.Item
                  label={item.fieldName}
                >
                  <div className={`${styles.form_item} ${styles.text_overflow_single}`} title={item && item.fieldValue}>{item && item.fieldValue}</div>
                </Form.Item>
              ))}
              <Form.Item>
                <div className={styles.column}>同步配置</div>
              </Form.Item>
              <Form.Item
                label="是否同步前清空历史数据"
              >
                <div className={`${styles.form_item} ${styles.text_overflow_single}`}>{data?.isTruncate ? '是' : '否'} </div>
              </Form.Item>
              <Form.Item
                label="是否开启文件写入模式"
              >
                <div className={`${styles.form_item} ${styles.text_overflow_single}`}>{data?.pgText === 1 ? '是' : '否'} </div>
              </Form.Item>
              {
                data?.pgText !== 1 && (
                  <>
                    <Form.Item
                      label="写入模式"
                      rules={[{ required: true, message: '请选择写入模' }]}
                    >
                      <div
                        className={`${styles.form_item} ${styles.text_overflow_single}`}
                        title={
                          data && {
                            1: '覆盖（Insert Overwrite）',
                            2: '追加（Insert Into）',
                            5: '主键冲突，替换原有数据',
                            6: '主键冲突，丢弃新数据',
                          }[data.dataReplaceRuleId]
                        }
                      >
                        {data && {
                          1: '覆盖（Insert Overwrite）',
                          2: '追加（Insert Into）',
                          5: '主键冲突，替换原有数据',
                          6: '主键冲突，丢弃新数据',
                        }[data.dataReplaceRuleId]}
                      </div>
                    </Form.Item>
                    <Form.Item
                      className={styles.check_bar}
                      label="脏数据限制"
                      style={{ marginTop: '.1rem' }}
                    >
                      <div className={`${styles.form_item} ${styles.text_overflow_single}`} title={`单次同步失败记录数超过${data && data.errorNumLimit || '-'}条则任务结束`}>单次同步失败记录数超过 {data && data.errorNumLimit} 条则任务结束</div>
                    </Form.Item>
                  </>
                )
              }
              <Form.Item
                label="生效日期"
              >
                <div className={`${styles.form_item} ${styles.text_overflow_single}`}>{data && data.schedule && `${data.schedule.effectiveDateStart} ~ ${data.schedule.effectiveDateEnd}`}</div>
              </Form.Item>
              <Form.Item
                label="调度周期"
              >
                <div className={`${styles.form_item} ${styles.text_overflow_single}`}>{data && data.schedule && ['月', '周', '天', '小时', '分钟'][data.schedule.cycle]}</div>
              </Form.Item>
              <Form.Item
                label="执行时间"
              >
                <div className={`${styles.form_item} ${styles.text_overflow_single}`}>{data && data.schedule && `${data.schedule.startTimeHour}:${data.schedule.startTimeMin} ${data.schedule.endTimeHour && data.schedule.endTimeMin ? ` ~ ${data.schedule.endTimeHour}:${data.schedule.endTimeMin}` : ''}`}</div>
              </Form.Item>
              {cycle === 0 || cycle === 1 || cycle === 3 || cycle === 4 ? (
                <Form.Item
                  label="调度间隔"
                >
                  <div className={`${styles.form_item} ${styles.text_overflow_single}`}>
                    {cycle === 0
                      && data && data.schedule && data.schedule.execPoint.split(',').map((item) => (<Tag>{`${item}号`}</Tag>))}
                    {cycle === 1
                      && data && data.schedule && data.schedule.execPoint.split(',').map((item) => (<Tag>{`${['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'][item - 1]}`}</Tag>))}
                    {cycle === 4
                      && data && data.schedule && data.schedule.execPoint.split(',').map((item) => (<Tag>{`${item}分钟`}</Tag>))}
                    {cycle === 3
                      && data && data.schedule && data.schedule.execPoint.split(',').map((item) => (<Tag>{`${item}小时`}</Tag>))}
                  </div>
                </Form.Item>
              ) : null}
              <Form.Item
                label="跨周期依赖"
              >
                <div className={`${styles.form_item} ${styles.text_overflow_single}`}>{data && data.schedule && ['不依赖上一周期', '等待上一周期结束'][data.schedule.cycleDependence]}</div>
              </Form.Item>
            </Form>
          </div>
        </div>
      </div>
    )
  }
}
